package com.tanhua.manage.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.templates.HuaWeiUGCTemplate;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.db.UserStatus;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.CommentVo;
import com.tanhua.domain.vo.MovementsVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.dubbo.api.*;
import com.tanhua.manage.utils.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;

@Service
public class UserService {

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private UserApi userApi;

    @Reference
    private VideoApi videoApi;

    @Reference
    private PublishApi publishApi;

    @Reference
    private CommentApi commentApi;

    @Reference
    private UserStatusApi userStatusApi;

    @Value("${tanhua.secret}")
    private String secret; // 读取yml密钥

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private HuaWeiUGCTemplate huaWeiUGCTemplate;

    private final String FREEZE_KEY = "FREEZE_KEY_"; // 定义账号状态的前缀

    private final String TOKEN_KEY = "TOKEN_KEY_"; // 定义token的前缀


    /**
     * 接口名称：用户数据翻页
     */
    public ResponseEntity<Object> findByPage(Integer page, Integer pagesize) {
        // 查询用户是否解冻
        // 调用服务提供者分页查询用户列表
        IPage<UserInfo> result = userInfoApi.findByPage(page, pagesize);
        for (UserInfo userInfo : result.getRecords()) {
            if (userInfo.getUserStatus().equals("2")) {
                String status = redisTemplate.opsForValue().get(FREEZE_KEY + userInfo.getId());
                System.out.println("status = " + status);
                if (status == null) {
                    userInfo.setUserStatus("1");
                    userInfoApi.update(userInfo); // 更新用户详情表中的状态
                }
            }
        }

        // 封装返回结果
        PageResult pageResult = new PageResult(page, pagesize, (int) result.getTotal(), result.getRecords());
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 用户基本资料
     */
    public ResponseEntity<Object> findById(Long userID) {
        UserInfo userInfo = userInfoApi.findById(userID);
        return ResponseEntity.ok(userInfo);
    }

    /**
     * 视频记录翻页
     */
    public ResponseEntity<Object> findVideosList(Long uid, Integer page, Integer pagesize) {
        // 1.调用服务提供者分页查询某用户的视频列表
        PageResult pageResult = videoApi.findVideosList(uid, page, pagesize);

        // 获取当前页的数据
        List<Video> videoList = (List<Video>) pageResult.getItems();

        // 2.封装返回结果
        List<VideoVo> voList = new ArrayList<>();
        if (videoList != null && videoList.size() > 0) {
            for (Video video : videoList) {
                // 2.1 创建vo
                VideoVo vo = new VideoVo();

                // 2.2 封装vo
                vo.setId(video.getId().toString());
                BeanUtils.copyProperties(video, vo);

                // 查询作者详情
                UserInfo userInfo = userInfoApi.findById(video.getUserId());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());

                vo.setSignature(video.getText());
                vo.setCover(video.getPicUrl());

                // 2.3 添加vo
                voList.add(vo);
            }
        }
        pageResult.setItems(voList);

        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：动态分页
     */
    public ResponseEntity<Object> findMovementsList(Integer page, Integer pagesize, Long uid, String state) {

        PageResult pageResult = null;
        if (state != null && !state.equals("''") && !state.equals("")) {//根据审核状态查询动态列表
            Long stateValue = Long.valueOf(state);
            pageResult = publishApi.queryPublishListByState(page, pagesize, stateValue);
        } else if (uid != null) {//根据id查询动态列表
            pageResult = publishApi.queryMyPublishList(page, pagesize, uid);
        } else {//查询所有动态列表
            pageResult = publishApi.queryAllPublishList(page, pagesize);
        }
        setMovementsVo(pageResult);

        return ResponseEntity.ok(pageResult);
    }

    /**
     * 封装结果数据公共方法
     */
    private void setMovementsVo(PageResult pageResult) {

        // 获取当前页的数据
        List<Publish> publishList = (List<Publish>) pageResult.getItems();

        // 3.封装返回结果
        List<MovementsVo> voList = new ArrayList<>();

        if (publishList != null && publishList.size() > 0) {
            for (Publish publish : publishList) {
                // 3.1 创建vo
                MovementsVo vo = new MovementsVo();

                // 3.2 封装数据
                // 封装动态信息
                BeanUtils.copyProperties(publish, vo);
                // 封装用户详情信息
                UserInfo userInfo = userInfoApi.findById(publish.getUserId());
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo, vo);
                    if (!StringUtils.isEmpty(userInfo.getTags())) {
                        String[] tags = userInfo.getTags().split(",");
                        vo.setTags(tags);
                    }
                }

                vo.setId(publish.getId().toString());
                if (publish.getMedias() != null) {
                    String[] medias = publish.getMedias().toArray(new String[]{});
                    vo.setImageContent(medias);
                }

                vo.setDistance("50米");
                // 格式化日期
                vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                        .format(new Date(publish.getCreated())));

                // 3.3 添加vo到voList
                voList.add(vo);
            }
        }

        // 4.重新设置pageResult中的items
        pageResult.setItems(voList);
    }

    /**
     * 接口名称：动态详情
     */
    public ResponseEntity<Object> findMovementsById(String publishId) {
        // 1.调用服务提供者api查询动态详情
        Publish publish = publishApi.findById(publishId);

        // 2.封装返回数据
        MovementsVo vo = new MovementsVo();

        // 封装数据
        // 封装动态信息
        BeanUtils.copyProperties(publish, vo);

        // 封装用户详情信息
        UserInfo userInfo = userInfoApi.findById(publish.getUserId());
        if (userInfo != null) {
            BeanUtils.copyProperties(userInfo, vo);
            if (!StringUtils.isEmpty(userInfo.getTags())) {
                String[] tags = userInfo.getTags().split(",");
                vo.setTags(tags);
            }
        }

        vo.setId(publish.getId().toString());
        if (publish.getMedias() != null) {
            String[] medias = publish.getMedias().toArray(new String[]{});
            vo.setImageContent(medias);
        }

        vo.setDistance("50米");
        // 格式化日期
        vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(new Date(publish.getCreated())));

        return ResponseEntity.ok(vo);
    }

    /**
     * 接口名称：评论列表翻页
     */
    public ResponseEntity<Object> findCommentsById(String publishId, Integer page, Integer pagesize) {
        // 1.调用服务提供者api，根据动态id查询评论列表，并分页
        PageResult pageResult = commentApi.queryCommentsList(publishId, page, pagesize);

        // 获取当前页的数据
        List<Comment> commentList = (List<Comment>) pageResult.getItems();

        // 2.封装返回数据
        List<CommentVo> voList = new ArrayList<>();
        if (commentList != null && commentList.size() > 0) {
            for (Comment comment : commentList) {
                // 2.1 创建vo
                CommentVo vo = new CommentVo();

                // 2.2 封装vo
                vo.setId(comment.getId().toString());

                // 查询评论人的详情
                UserInfo userInfo = userInfoApi.findById(comment.getUserId());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());

                vo.setContent(comment.getContent());
                // 日期格式化
                vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(comment.getCreated())));
                vo.setLikeCount(comment.getLikeCount());
                vo.setHasLiked(0);

                // 2.3 添加vo到集合
                voList.add(vo);
            }
        }

        // 3.重新设置items的值
        pageResult.setItems(voList);

        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：用户冻结操作
     *
     * @param map
     * @return
     */
    public ResponseEntity<Object> freeze(Map<String, Object> map) {
        UserStatus userStatus = new UserStatus();
        userStatus.setUserId(Long.valueOf(map.get("userId").toString())); // 用户ID
        userStatus.setFreezingTime(Integer.valueOf(map.get("freezingTime").toString())); // 冻结时间
        userStatus.setFreezingRange(Integer.valueOf(map.get("freezingRange").toString())); // 冻结范围
        userStatus.setReasonsForFreezing(map.get("reasonsForFreezing").toString()); // 冻结原因
        userStatus.setFrozenRemarks(map.get("frozenRemarks").toString()); // 冻结备注
        userStatus.setCreated(System.currentTimeMillis()); // 禁封时间
        userStatus.setStatus(2);
        UserInfo userInfo = userInfoApi.findById(userStatus.getUserId());
        userInfo.setUserStatus("2"); // 冻结
        userInfoApi.update(userInfo);
        switch (userStatus.getFreezingTime()) {
            case 1:
                userStatus.setThawingTime(System.currentTimeMillis() + 259200000); // 解封时间
                //往Redis设置冻结信息，并设置过期时间（解封时间）(封3天)
                redisTemplate.opsForValue().set(FREEZE_KEY + userInfo.getId(), map.get("freezingRange").toString(), Duration.ofDays(3));
                break;
            case 2:
                userStatus.setThawingTime(System.currentTimeMillis() + 604800000); // 解封时间
                //往Redis设置冻结信息，并设置过期时间（解封时间）(封7天)
                redisTemplate.opsForValue().set(FREEZE_KEY + userInfo.getId(), map.get("freezingRange").toString(), Duration.ofDays(7));
                break;
            default:
                //往Redis设置冻结信息，并设置过期时间（解封时间）(封永久)
                redisTemplate.opsForValue().set(FREEZE_KEY + userInfo.getId(), map.get("freezingRange").toString());
        }
        userStatusApi.save(userStatus);
        // 等于1 登录被禁封，应该强制用户下线
        if (userStatus.getFreezingRange() == 1) {
            User user = userApi.findById(userInfo.getId());
            // 【加密得到token】
            String token = JwtUtils.createToken(user.getId(), user.getMobile(), secret);
            redisTemplate.delete(TOKEN_KEY + token);
        }

        // 返回结果
        Map<String, String> message = new HashMap<>();
        message.put("message", "操作成功");
        return ResponseEntity.ok(message);
    }

    /**
     * 用户解冻操作
     */
    public ResponseEntity<Object> unfreeze(Map<String, Object> map) {
        Long userId = Long.valueOf(map.get("userId").toString()); // 用户ID
        String frozenRemarks = map.get("frozenRemarks").toString(); // 解封原因
        userStatusApi.unfreeze(userId, frozenRemarks);
        UserInfo userInfo = userInfoApi.findById(userId);
        userInfo.setUserStatus("1");
        userInfoApi.update(userInfo);
        redisTemplate.delete(FREEZE_KEY + userId);
        // 返回结果
        Map<String, String> message = new HashMap<>();
        message.put("message", "操作成功");
        return ResponseEntity.ok(message);
    }


    /**
     * 接口名称：动态拒绝
     */
    public ResponseEntity<Object> publishReject(String[] publishIds) {
        //将动态表中对应动态id的审核状态修改为state
        String message = publishApi.changePublishStateAll(publishIds, 2);
        Map<String, String> map = new HashMap<>();
        map.put("message", message);
        return ResponseEntity.ok(JSON.toJSONString(map));
    }

    /**
     * 接口名称：动态通过
     */
    public ResponseEntity<Object> publishPass(String[] publishIds) {
        //华为云内容审核实现动态复审通过功能
        if (publishIds != null) {
            for (String publishId : publishIds) {
                //根据动态id查询动态对象
                Publish publish = publishApi.findById(publishId);
                //审核动态内容
                if (publish != null) {
                    Integer state = publish.getState();
                    //审核文字
                    boolean textContentCheck = huaWeiUGCTemplate.textContentCheck(publish.getTextContent());
                    if (textContentCheck) {
                        //审核文字成功后，再审核图片
                        boolean imageContentCheck = huaWeiUGCTemplate.imageContentCheck(publish.getMedias().toArray(new String[]{}));
                        if (imageContentCheck) {
                            state = 1; // 审核通过
                        } else {
                            state = 2; // 审核不通过
                        }
                    } else {
                        state = 2; // 审核不通过
                    }
                    //调用服务提供者更新动态的状态
                    publishApi.updateState(publishId, state);
                }
            }
        }
        String message = "审核通过";
        //查询数据是否都审核通过,返回未审核通过的动态集合
        List<Publish> publishList = publishApi.isPass(publishIds);
        if (publishList != null && publishList.size() != 0) {
            message = "审核未通过";
        }
        Map<String, String> map = new HashMap<>();
        map.put("message", message);
        return ResponseEntity.ok(JSON.toJSONString(map));
    }
}
